﻿using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace VisualWip.PresentationModel
{
    public class NameToImageSourceConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof (ImageSource))
                throw new InvalidOperationException("Target type must be System.Windows.Media.ImageSource.");

            var assignedTo = value as string;

            string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //+ @"\Images\";
            string imagePath = Path.Combine(directoryName, @"images");


            var fileTypes = new[] {"jpg", "jpeg", "png", "gif", "bpm"};

            foreach (string fileType in fileTypes)
            {
                string fileName = string.Format("{0}.{1}", assignedTo, fileType);
                var x = new FileInfo(Path.Combine(imagePath, fileName));
                if (x.Exists)
                {
                    try
                    {
                        var img = new BitmapImage();
                        img.BeginInit();
                        img.UriSource = new System.Uri(x.FullName);
                        img.EndInit();
                        return img;
                    }
                    catch
                    {
                        return DependencyProperty.UnsetValue;
                    }
                }
            }

            return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}